import Axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type CustomParamsSerializer
} from 'axios'
import { stringify } from 'qs'
import { getToken, formatToken } from '@/utils/auth'
import { useUserStore } from '@/stores/modules/user'
import type { HttpError, HttpResponse, RequestMethods } from './types'

const defaultConfig: AxiosRequestConfig = {
  // 请求超时时间
  timeout: 10000,
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  },
  // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
  paramsSerializer: {
    serialize: stringify as unknown as CustomParamsSerializer
  }
}

class RequestHttp {
  constructor() {
    this.httpInterceptorsRequest()
    this.httpInterceptorsResponse()
  }

  /** `token`过期后，暂存待执行的请求 */
  private static requests: ((token: string) => void)[] = []

  /** 防止重复刷新`token` */
  private static isRefreshing = false

  /** 初始化配置对象 */
  private static initConfig: AxiosRequestConfig = {}

  /** 保存当前`Axios`实例对象 */
  private static axiosInstance: AxiosInstance = Axios.create(defaultConfig)

  /** 重连原始请求 */
  private static retryOriginalRequest(config: AxiosRequestConfig) {
    return new Promise((resolve) => {
      RequestHttp.requests.push((token: string) => {
        config.headers!['Authorization'] = formatToken(token)
        resolve(config)
      })
    })
  }

  /** 请求拦截 */
  private httpInterceptorsRequest(): void {
    RequestHttp.axiosInstance.interceptors.request.use(
      async (config: AxiosRequestConfig): Promise<any> => {
        /** 请求白名单，放置一些不需要`token`的接口（通过设置请求白名单，防止`token`过期后再请求造成的死循环问题） */
        const whiteList = ['/refresh-token', '/login']
        return whiteList.some((url) => config.url!.endsWith(url))
          ? config
          : new Promise((resolve) => {
              const data = getToken()
              if (data) {
                const now = new Date().getTime()
                const expired = parseInt(data.expires) - now <= 0
                if (expired) {
                  if (!RequestHttp.isRefreshing) {
                    RequestHttp.isRefreshing = true
                    // token过期刷新
                    useUserStore()
                      .handRefreshToken({ refreshToken: data.refreshToken })
                      .then((res: any) => {
                        const token = res?.data?.accessToken
                        config.headers!['Authorization'] = formatToken(token)
                        RequestHttp.requests.forEach((cb) => cb(token))
                        RequestHttp.requests = []
                      })
                      .finally(() => {
                        RequestHttp.isRefreshing = false
                      })
                  }
                  resolve(RequestHttp.retryOriginalRequest(config))
                } else {
                  config.headers!['Authorization'] = formatToken(data.accessToken)
                  resolve(config)
                }
              } else {
                resolve(config)
              }
            })
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  }

  /** 响应拦截 */
  private httpInterceptorsResponse(): void {
    const instance = RequestHttp.axiosInstance
    instance.interceptors.response.use(
      (response: HttpResponse) => {
        if (response.data.success) {
          return response.data.data
        } else {
          return Promise.reject(response.data)
        }
      },
      (error: HttpError) => {
        const $error = error
        $error.isCancelRequest = Axios.isCancel($error)
        // 所有的响应异常 区分来源为取消请求/非取消请求
        return Promise.reject($error)
      }
    )
  }

  /** 通用请求工具函数 */
  public request<T>(
    method: RequestMethods,
    url: string,
    param?: AxiosRequestConfig,
    axiosConfig?: AxiosRequestConfig
  ): Promise<T> {
    const config = {
      method,
      url,
      ...param,
      ...axiosConfig
    } as AxiosRequestConfig

    // 单独处理自定义请求/响应回调
    return new Promise((resolve, reject) => {
      RequestHttp.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  /** 单独抽离的`post`工具函数 */
  public post<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.request<T>('post', url, params, config)
  }

  /** 单独抽离的`get`工具函数 */
  public get<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.request<T>('get', url, params, config)
  }
}

export const http = new RequestHttp()
